package com.mingyizhudao.app.view.login;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.PushManager;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.utils.ToastUtil;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.notify.NotifyBean.ADNotify;

public class LoginActivity2 extends MYBaseActivity{

	private View by_pwd,by_phone,login_by_pwd,login_by_phone;
	private TimeCount timeCount;
	private TextView btn_getsmscode;
	private EditText et_phone_phone,et_pwd_phone,et_pwd,et_phonecode;
	
	private ADNotify adNotify;
	@Override
	public void initHeaderView() {
		setTopViewBg(R.color.actionbar_bg_color);
		initBackView(R.drawable.left_back_white_icon, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		setTitleViewValue(0, 0, R.color.white);
		setTitleViewValue("登录");
		
		
		setRightText( "注册" ,R.color.white);
		initOptionView(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				IntentHelper.getInstance(activity).gotoActivity(RegisterActivity.class);
				//finish();
			}
		});
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login1);
		initView();
	}
	
	private void initView(){
		by_pwd = findViewById(R.id.by_pwd);
		by_phone = findViewById(R.id.by_phone);
		login_by_pwd = findViewById(R.id.login_by_pwd);
		login_by_phone = findViewById(R.id.login_by_phone);
		
		et_phone_phone = (EditText) findViewById(R.id.et_phone_phone);
		et_pwd_phone = (EditText) findViewById(R.id.et_pwd_phone);
		et_pwd = (EditText) findViewById(R.id.et_pwd);
		et_phonecode = (EditText) findViewById(R.id.et_phonecode);
		
		btn_getsmscode = (TextView) findViewById(R.id.btn_getsmscode);
		
		timeCount = new TimeCount(60000, 1000);// 构造CountDownTimer对象
		
		findViewById(R.id.tv_changepassword).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				IntentHelper.getInstance(activity).gotoActivity(ChangePassWordActivity.class);
			}
		});
		
		adNotify = (ADNotify) getIntent().getSerializableExtra("adNotify");
		
	}
	
	public void onSmsCode(View view) {
		
		String phoneStr = et_phone_phone.getText().toString().trim();
		if(Utils.checkMobile(phoneStr)){
			LoadingDialog.getInstance(activity).show();
			timeCount.start();// 开始计时
			Map params = new HashMap<String , Object>();
			params.put("mobile", phoneStr);
			params.put("action_type", 102);
			params.put("key", "smsVerifyCode");
			
			String url = CommonUtils.getSendCodeUrl(activity);
			postHttpResult(url, params, Constants.HTTP_INDEX.First, new TypeToken<QjResult<Map<String, Object>>>() {});
		}else{
			ToastUtil.showToast(activity, "请核对你的手机号");
		}
	}
	
	public void doLoginByPhone(View view){
		
		String phoneStr = et_phone_phone.getText().toString().trim();
		String codeStr = et_phonecode.getText().toString().trim();
		if(!Utils.checkMobile(phoneStr)){
			ToastUtil.showToast(activity, "请核对你的手机号");
			return;
		}
		if(Utils.isStringEmpty(codeStr)){
			ToastUtil.showToast(activity, "请输入手机验证码");
			return;
		}
		LoadingDialog.getInstance(activity).show();
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("username", phoneStr);
		params.put("verify_code", codeStr);// 验证码
		params.put("key", "userLogin");
		String url = CommonUtils.getLoginUrl(activity);
		postHttpResult(url, params, Constants.HTTP_INDEX.Second, new TypeToken<QjResult<Map<String, Object>>>() {});
		CommonUtils.setMobile(activity, phoneStr);
	}
	HashMap<String, Object> params = new HashMap<String, Object>();
	public void doLoginByPwd(View view){
		
		String phoneStr = et_pwd_phone.getText().toString().trim();
		String pwdStr = et_pwd.getText().toString().trim();
		if(!Utils.checkMobile(phoneStr)){
			ToastUtil.showToast(activity, "请核对你的手机号");
			return;
		}
		if(Utils.isStringEmpty(pwdStr)){
			ToastUtil.showToast(activity, "请输入密码");
			return;
		}
		if(pwdStr.length()<6){
			ToastUtil.showToast(activity, "密码至少6位！");
			return;
		}
		
		params.put("username", phoneStr);
		params.put("password", pwdStr);// 验证码
		params.put("key", "userLogin");
		LoadingDialog.getInstance(activity).show();
		
		String url = CommonUtils.getLoginByPwdUrl(activity);
		postHttpResult(url, params, Constants.HTTP_INDEX.Third, new TypeToken<QjResult<Map<String, Object>>>() {});
		CommonUtils.setMobile(activity, phoneStr);
	}
	
	@Override
	public void onSuccess(QjResult result, String flg) {
		super.onSuccess(result, flg);
		if(flg.equals(Constants.HTTP_INDEX.First)){
			Toast.makeText(activity, "验证码已发送，注意查收！", 0)
			.show();
		}else if(flg.equals(Constants.HTTP_INDEX.Second)){
			Map<String, Object> map = (Map<String, Object>) result.getResults();
			if(map != null && !map.isEmpty()){
				String token = map.get("token")+"";
				Object object = map.get("is_new_user");
				if(object != null){
				    double is_new_user = Double.parseDouble(object+""); 
					if(is_new_user == 2){
						StatService.onEvent(activity, "register", "eventLabel", 1);
					}
				}
				CommonUtils.setToken(activity, token);
//				setAlias();//设置别名
				setGeTuiAlias();
				if (adNotify!=null) {
					try
					{	
					Bundle bundle2 = new Bundle();
					Class<?> cName = Class.forName(adNotify.getClassname());
					Map<String,Object> param =  adNotify.getParam();
					for (Map.Entry<String, Object> entry : param.entrySet()) {
						String key = entry.getKey();
						String value = entry.getValue().toString();
						bundle2.putString(key, value);
					} 
					
					
					//打开自定义的Activity
					Intent i = new Intent(activity, cName);
					i.putExtras(bundle2);
					//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
					activity.startActivity(i);
					}
					catch( Exception e )
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
					
				}
				
				finish();
			}
		}else if(flg.equals(Constants.HTTP_INDEX.Third)){
			Map<String, Object> map = (Map<String, Object>) result.getResults();
			if(map != null && !map.isEmpty()){
				String token = map.get("token")+"";
				CommonUtils.setToken(activity, token);
//				setAlias();//设置别名
				setGeTuiAlias();
				if (adNotify!=null) {
					try
					{	
					Bundle bundle2 = new Bundle();
					Class<?> cName = Class.forName(adNotify.getClassname());
					Map<String,Object> param =  adNotify.getParam();
					for (Map.Entry<String, Object> entry : param.entrySet()) {
						String key = entry.getKey();
						String value = entry.getValue().toString();
						bundle2.putString(key, value);
					} 
					
					
					//打开自定义的Activity
					Intent i = new Intent(activity, cName);
					i.putExtras(bundle2);
					//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
					activity.startActivity(i);
					}
					catch( Exception e )
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
					
				}
				
				finish();
			}
		}
	}
	
	@Override
	public void onFailure(QjResult result, String flg) {
		super.onFailure(result, flg);
		if(flg.equals(Constants.HTTP_INDEX.First)){
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					Toast.makeText(activity, "验证码发送失败！", 0).show();
					timeCount.cancel();
					btn_getsmscode.setText("获取验证码");
					btn_getsmscode.setClickable(true);
					btn_getsmscode.setBackgroundColor(getResources().getColor(R.color.white));	
				}
			});
		}
	}
	
	@Override
	public void onCompleted(Exception e, String flg) {
		super.onCompleted(e, flg);
		LoadingDialog.getInstance(activity).dismiss();
	}
	
	
	public void onMenuChange(View view){
		if(view.getId() == R.id.rb1){
			by_pwd.setVisibility(View.VISIBLE);
			by_phone.setVisibility(View.INVISIBLE);
			login_by_pwd.setVisibility(View.VISIBLE);
			login_by_phone.setVisibility(View.GONE);
		}
		
		if(view.getId() == R.id.rb2){
			by_phone.setVisibility(View.VISIBLE);
			by_pwd.setVisibility(View.INVISIBLE);
			login_by_phone.setVisibility(View.VISIBLE);
			login_by_pwd.setVisibility(View.GONE);
		}
		
	}
	

	
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_getsmscode.setText("获取验证码");
			btn_getsmscode.setClickable(true);
			btn_getsmscode.setBackgroundColor(getResources().getColor(R.color.white));
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_getsmscode.setClickable(false);
			btn_getsmscode.setText(millisUntilFinished / 1000 + "秒后重发");
			btn_getsmscode.setBackgroundColor(getResources().getColor(R.color.actionbar_bg_color));
		}
	}
	
	private void setGeTuiAlias() {
	String mobile =CommonUtils.getMobile( activity );
    String alias = "m_"+mobile;
    
    alias = Utils.Md5String(alias);
    
    if (TextUtils.isEmpty(alias)) {
        //Toast.makeText(activity,"别名不能为空！", Toast.LENGTH_SHORT).show();
        return;
    }
    if (!CommonUtils.isValidTagAndAlias(alias)) {
        //Toast.makeText(activity,"无效的别名！", Toast.LENGTH_SHORT).show();
        return;
    }

    // 设置别名
    
    PushManager.getInstance().bindAlias(activity, alias);
}
	
	
	
//	private static final int MSG_SET_ALIAS = 1001;
//	private final Handler mHandler = new Handler() {
//	@Override
//	    public void handleMessage(android.os.Message msg) {
//	        super.handleMessage(msg);
//	        switch (msg.what) {
//	            case MSG_SET_ALIAS:
//	                // 调用 JPush 接口来设置别名。
//	                JPushInterface.setAliasAndTags(getApplicationContext(),
//	                                                (String) msg.obj,
//	                                                 null,
//	                                                 mAliasCallback);
//	            break;
//	        default:
//	        }
//	    }                                       
//	};
//	
//	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
//	    @Override
//	    public void gotResult(int code, String alias, Set<String> tags) {
//	        switch (code) {
//	        case 0:
//	            // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
//	        	
//	            break;
//	        case 6002:
//	            // 延迟 60 秒来调用 Handler 设置别名
//	            mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
//	            break;
//	        default:
//	        }
//	    }
//	};
//	
//	private void setAlias() {
//		String mobile =CommonUtils.getMobile( activity );
//	    String alias = "m_"+mobile;
//	    
//	    alias = Utils.Md5String(alias);
//	    
//	    if (TextUtils.isEmpty(alias)) {
//	        //Toast.makeText(activity,"别名不能为空！", Toast.LENGTH_SHORT).show();
//	        return;
//	    }
//	    if (!CommonUtils.isValidTagAndAlias(alias)) {
//	        //Toast.makeText(activity,"无效的别名！", Toast.LENGTH_SHORT).show();
//	        return;
//	    }
//
//	    // 调用 Handler 来异步设置别名
//	    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
//	}
	
}
